package com.tange.ai.core.demo.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.tange.ai.core.demo.R;
import com.tange.ai.core.demo.add.AddTypeChooseActivity;
import com.tange.ai.core.demo.databinding.FragmentHomeBinding;
import com.tange.ai.core.demo.player.PlayerActivity;
import com.tange.core.backend.service.request.Http;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.core.data.structure.Device;
import com.tange.module.camera.query.DeviceCoreQuery;
import com.tg.appcommon.android.TGLog;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";

    private static final String CLOUD_API_DEVICE_LIST = "/app/v1/device/list";
    private static final String PARAM_PAGE_INDEX = "page";
    private static final String PARAM_PAGE_LIMIT = "limit";

    private FragmentHomeBinding binding;

    private ListAdapter listAdapter;

    private Disposable disposable;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        listAdapter = new ListAdapter();
        binding.apList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        binding.apList.setAdapter(listAdapter);

        binding.add.setOnClickListener(v -> startActivity(new Intent(getActivity(), AddTypeChooseActivity.class)));

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshDeviceList();
    }


    private void refreshDeviceList() {

        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

        binding.loading.setVisibility(View.VISIBLE);

        disposable = DeviceCoreQuery.INSTANCE.queryPage(1, 100, "").subscribe(devices -> {
            if (devices != null && devices.size() > 0) {
                listAdapter.refresh(devices);
                binding.emptyView.setVisibility(View.GONE);
            } else {
                binding.emptyView.setVisibility(View.VISIBLE);
            }
            binding.loading.setVisibility(View.GONE);
        }, throwable -> {
            binding.loading.setVisibility(View.GONE);
            Toast.makeText(getActivity(), "请求失败：" + throwable, Toast.LENGTH_LONG).show();
            TGLog.i(TAG, "[refreshDeviceList] throwable = " + throwable);
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {

        private List<Device> apList = new ArrayList<>();

        private boolean isAp = false;

        public void refresh(List<Device> list) {
            this.apList.clear();
            this.apList.addAll(list);
            notifyDataSetChanged();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device_list, viewGroup, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            final Device item = apList.get(position);
            viewHolder.name.setText(item.getName());
            viewHolder.offline.setText(item.online() ? "在线" : "离线");
            viewHolder.offline.setTextColor(item.online() ? getResources().getColor(R.color.green) : getResources().getColor(R.color.gray));

            Glide.with(getActivity()).load(item.getCover()).apply(RequestOptions.bitmapTransform(new RoundedCorners(25))).into(viewHolder.cover);

            viewHolder.itemView.setOnClickListener(view -> {
                PlayerActivity.launch(getContext(), item);
            });
        }

        @Override
        public int getItemCount() {
            return apList.size();
        }
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public final ImageView cover;
        public final TextView name;
        public final TextView offline;

        public ViewHolder(View view) {
            super(view);
            cover = view.findViewById(R.id.cover);
            name = view.findViewById(R.id.name);
            offline = view.findViewById(R.id.online);
        }
    }
}